package com.naughty.userlogin02.controller;

import com.alibaba.fastjson.JSON;
import com.naughty.userlogin02.bean.*;
import com.naughty.userlogin02.dao.UserDao;
import org.apache.ibatis.annotations.Param;
import org.apache.tomcat.jni.Directory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.FilterConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.MathContext;
import java.nio.file.Path;
import java.text.SimpleDateFormat;
import java.util.*;


@RestController
public class UserConteroller {

    int count=0;
    int number=0;
    @Autowired
    UserDao userDao;


    @CrossOrigin
    @RequestMapping("/login")
    public String userLogin(@RequestBody User user, HttpServletRequest request) {
        System.out.println("User : " + user);
        String str = "error";
        int count = userDao.getUserByMassage(user.getUsername(), user.getPassword());
       request.setAttribute("username",user.getUsername());


        System.out.println(user.getUsername());
        if (count > 0) {
            str = "ok";
        }
        return str;
    }
   @CrossOrigin
    @RequestMapping("/allUser")
    public String getUserList(QueryInfo queryInfo){
        System.out.println(queryInfo);
        int numbers = userDao.getUserCounts("%"+queryInfo.getQuery()+"%");// 获取数据总数
        int pageStart = (queryInfo.getPageNum()-1)*queryInfo.getPageSize();
        List<User> users = userDao.getAllUser("%"+queryInfo.getQuery()+"%",pageStart,queryInfo.getPageSize());
        HashMap<String, Object> res = new HashMap<>();
        res.put("numbers",numbers);
        res.put("data",users);
        System.out.println("总条数："+numbers);
        String users_json = JSON.toJSONString(res);
        return users_json;
    }
   @CrossOrigin
    @RequestMapping("/allFile")
    public String getFileList(QueryInfo queryInfos,@Param("user") String user){
        System.out.println(user);
        System.out.println(queryInfos);
        int numbers = userDao.getUserCounts("%"+queryInfos.getQuery()+"%");// 获取数据总数
        int pageStart = (queryInfos.getPageNum()-1)*queryInfos.getPageSize();
        List<Doc> docs = userDao.getAllFile(user,"%"+queryInfos.getQuery()+"%",pageStart,queryInfos.getPageSize());
       for (Doc doc:docs){
           System.out.println(docs.toString());
       }
        HashMap<String, Object> res = new HashMap<>();
        res.put("numbers",numbers);
        res.put("data",docs);
        System.out.println("总条数："+numbers);
        String users_json = JSON.toJSONString(res);
        return users_json;
    }

    @RequestMapping("/userState")
    public String updateUserState(@RequestParam("id") Integer  id,
                                  @RequestParam("state") Boolean state){
        int i = userDao.updateState(id, state);
        System.out.println("用户编号:"+id);
        System.out.println("用户状态:"+state);
        String str = i >0?"success":"error";
        return str;
    }

    @RequestMapping("/states")
    public String updateState(@RequestParam("id") Integer  id,
                                  @RequestParam("state") Boolean state){
        int i = userDao.updateDoc(id, state);
        System.out.println("用户编号:"+id);
        System.out.println("用户状态:"+state);
        String str = i >0?"success":"error";
        return str;
    }
    @RequestMapping("/state")
    public String update(@RequestParam("id") Integer  id,
                              @RequestParam("state") Boolean state){
        int i = userDao.updateImg(id, state);
        System.out.println("用户编号:"+id);
        System.out.println("用户状态:"+state);
        String str = i >0?"success":"error";
        return str;
    }

    @RequestMapping("/addUser")
    public String addUser(@RequestBody User user){
        System.out.println(user);
        user.setRole("普通用户");
        user.setState(false);
        int i = userDao.addUser(user);
        String str = i >0?"success":"error";
        return str;
    }

    @RequestMapping("/getUpdate")
    public String getUpdateUser(int id){
        System.out.println("编号:"+id);
        User updateUser = userDao.getUpdateUser(id);
        String users_json = JSON.toJSONString(updateUser);
        return users_json;
    }

    @RequestMapping("/editUser")
    public String editUser(@RequestBody User user){
        System.out.println(user);
        int i = userDao.editUser(user);
        String str = i >0?"success":"error";
        return str;
    }

    @RequestMapping("/deleteUser")
    public String deleteUser(int id){
        System.out.println(id);
        int i = userDao.deleteUser(id);
        String str = i >0?"success":"error";
        return str;
    }
    @RequestMapping("/deleteFile")
    public String deleteFile(int id){
        System.out.println(id);
        int i = userDao.deleteFile(id);
        String str = i >0?"success":"error";
        return str;
    }
    @RequestMapping("/deletepic")
    public String deletepic(int id){
        int i=userDao.deletePic(id);
        String str=i>0?"success":"error";
        return str;
    }
    @RequestMapping("/goods")
    public List<Good> goodList(){
      List<Good> goods= userDao.goods();
      for(Good good:goods){
          System.out.println(good.toString());
      }
      return goods;

    }
    @RequestMapping("/addgood")
    public String addgood(@RequestBody Good good){
        SimpleDateFormat day=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date da=new Date();
        String date= day.format(da);
        good.setDate(date);
        count++;
        good.setId(count);
        int i=userDao.insertGood(good);


        String number =i>0 ?"success":"error";
        System.out.println(good.toString());
        return number;


    }


    @RequestMapping("/addcontent")
    public String addcontent( Boke boke){

        System.out.println(boke.getContent());
        int rows=userDao.addcontent(boke);

        String number=rows>0?"success":"error";
        return number;
    }
    @RequestMapping("/upload")
    public Object multiUpload(@RequestParam("file")MultipartFile[] files,HttpServletRequest request,@Param("user") String user,@Param("fname") String fname){
        System.out.println("文件的个数:"+files.length);
        System.out.println(user);
        for (MultipartFile f : files){
            saveFile(f,request,user,fname);
        }
        return "ok";
    }



    private Object saveFile(MultipartFile file,HttpServletRequest request,@Param("user") String user,@Param("fname") String fname){



        count++;
        if (file.isEmpty()){
            return "未选择文件";
        }
        double result;
        String unit="字节";
        long length = file.getSize();
        if(length<1024)
        {
            result= length;
        }
        else if(length<1024*1024)
        {
            result=length/1024.0;
            unit="KB";
        }
        else if(length<1024*1024*1024)
        {
            result=length/1024.0/1024;
            unit="MB";
        }
        else
        {
            result=length/1024.0/1024/1024;
            unit="GB";
        }

        BigDecimal bigDecimal=new BigDecimal(result+"",new MathContext(3));
//        return bigDecimal.doubleValue()+unit;
       String max=bigDecimal.doubleValue()+unit;

        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:s");

        Date date=new Date();
        String day=simpleDateFormat.format(date);
        String filename = file.getOriginalFilename(); //获取上传文件原来的名称

        String dir=request.getServletContext().getRealPath("");


        System.out.println(user);
        System.out.println(fname);
        System.out.println(filename);
        Doc doc=new Doc(count,filename,day,number,max,user,fname);

        Picture picture=new Picture(count,day,filename,max,number,user,fname);
        Video video=new Video(count,filename,day,max,number,user);
        if(filename.endsWith(".png")||filename.endsWith(".jpg")){
            userDao.addpicture(picture);
        }
      if(filename.endsWith(".mp4")||filename.endsWith(".mp3")||filename.endsWith(".wmv")){
           userDao.addvideo(video);
        }

       if(filename.endsWith(".doc")||filename.endsWith(".docx")||filename.endsWith(".xls")||filename.endsWith(".sql")||filename.endsWith(".cpp")||filename.endsWith(".pdf")||filename.endsWith(".xlsx")){
            userDao.addfile(doc);
        }


        File temp = new File(dir);
        if (!temp.exists()){
            temp.mkdirs();
        }

        File localFile = new File(dir+filename);
        try {
            file.transferTo(localFile); //把上传的文件保存至本地
            System.out.println(file.getOriginalFilename()+" 上传成功");
        }catch (IOException e){
            e.printStackTrace();
            return "上传失败";
        }

        return "ok";
    }
    @CrossOrigin
    @PostMapping(value = "/api/uploadVidoe3")
    @ResponseBody
    public Map<String,String> savaVideotest(@RequestParam("file") MultipartFile file,@Param("user") String user,@RequestParam String Context,HttpServletRequest request)
            throws IllegalStateException {
        Map<String,String> resultMap = new HashMap<>();
        try{
            //获取文件后缀，因此此后端代码可接收一切文件，上传格式前端限定
            String fileExt = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1)
                    .toLowerCase();
            // 重构文件名称
//            System.out.println("前端传递的保存路径："+SavePath);
//            String pikId = UUID.randomUUID().toString().replaceAll("-", "");
//            String newVidoeName = pikId + "." + fileExt;
//            System.out.println("重构文件名防止上传同名文件："+newVidoeName);
//            //保存视频
//
//            File fileSave = new File(SavePath, newVidoeName);
//            System.out.println(fileSave);
//            file.transferTo(fileSave);
//
//            //构造Map将视频信息返回给前端
//            //视频名称重构后的名称
//            resultMap.put("newVidoeName",newVidoeName);
//            //正确保存视频则设置返回码为200
//            resultMap.put("resCode","200");
//            //返回视频保存路径
//            resultMap.put("VideoUrl",SavePath + "/" + newVidoeName);

            count++;
            if (file.isEmpty()){

            }
            double result;
            String unit="字节";
            long length = file.getSize();
            if(length<1024)
            {
                result= length;
            }
            else if(length<1024*1024)
            {
                result=length/1024.0;
                unit="KB";
            }
            else if(length<1024*1024*1024)
            {
                result=length/1024.0/1024;
                unit="MB";
            }
            else
            {
                result=length/1024.0/1024/1024;
                unit="GB";
            }

            BigDecimal bigDecimal=new BigDecimal(result+"",new MathContext(3));
//        return bigDecimal.doubleValue()+unit;
            String max=bigDecimal.doubleValue()+unit;

            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:s");

            Date date=new Date();
            String day=simpleDateFormat.format(date);
            String filename = file.getOriginalFilename(); //获取上传文件原来的名称

            String dir=request.getServletContext().getRealPath("");
            System.out.println(Context);

            System.out.println(user);

            System.out.println(filename);


            Video video=new Video(count,filename,day,max,number,user);


                userDao.addvideo(video);




            File temp = new File(dir);
            if (!temp.exists()){
                temp.mkdirs();
            }

            File localFile = new File(dir+filename);
            try {
                file.transferTo(localFile); //把上传的文件保存至本地
                System.out.println(file.getOriginalFilename()+" 上传成功");
            }catch (IOException e){
                e.printStackTrace();

            }




            return  resultMap;

        }catch (Exception e){
            e.printStackTrace();
            e.getMessage();
            //保存视频错误则设置返回码为400
            resultMap.put("resCode","400");
            return  resultMap ;

        }
    }
    @RequestMapping("/file")
    @ResponseBody
   public List<Doc> filelist(@Param("user") String user){
        List<Doc> list=userDao.filelist(user);
        for (Doc doc:list){
            System.out.println(doc.toString());
        }
       return list;
    }
    @RequestMapping("/foc")
    @ResponseBody
    public List<Doc> docList(@Param("fname") String fname,@Param("user") String user){
        System.out.println(fname);
        System.out.println(user);
        List<Doc> list=userDao.file(fname,user);
        for (Doc doc:list){
            System.out.println(doc.toString());
        }
        return list;
    }
    @RequestMapping("/pictu")
    @ResponseBody
    public List<Picture> pictureList(@Param("user") String user,@Param("fname") String fname){
        List<Picture> pics=userDao.piolist(user, fname);
        System.out.println(user);
        System.out.println(fname);
        for (Picture picture:pics){
            System.out.println(picture.getCtime());
        }
        return pics;
    }
   @RequestMapping("/picture")
    @ResponseBody
    public List<Picture> pictureList(@Param("user") String user){
       System.out.println(user);
        return userDao.piclist(user);
   }

   @RequestMapping("/delete")
    @ResponseBody
    public int deldoc(@Param("id") Integer id){

        return userDao.deletedoc(id);
   }
  @RequestMapping("/video")
  @ResponseBody
  public List<Video> videoList(@Param("user") String user){
        List<Video> list=userDao.videolist(user);
        for(Video video:list){
            System.out.println(video.getVname());
        }
        return list;
  }
  @RequestMapping("/doc")
  @ResponseBody
    public List<Doc> docs(@Param("user") String user){
        return userDao.doclist(user);
  }
  @RequestMapping("/img")
    @ResponseBody
    public List<Picture> pList(@Param("user") String user){
        return userDao.imglist(user);
  }
    @RequestMapping("/docs")
    @ResponseBody
    public List<Doc> docs(){
        return userDao.docs();
    }
    @RequestMapping("/imgs")
    @ResponseBody
    public List<Picture> pList(){
        return userDao.imgs();
    }
  @RequestMapping("/floder")

    public String addfloder(@RequestBody Floder floder,@Param("user") String user){
      SimpleDateFormat day=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      Date da=new Date();
      String date= day.format(da);
      floder.setCtime(date);
      count++;
      floder.setId(count);
      floder.setUser(user);
      System.out.println(user);
      int i=userDao.addFloder(floder);


      String number =i>0 ?"success":"error";
      System.out.println(floder.toString());
      return number;
  }
   @RequestMapping("floders")
   @ResponseBody
    public List<Floder> selectfloder(@Param("user") String user){
         System.out.println(user);
      List<Floder> floders=userDao.floders(user);
      for(Floder floder:floders){
          System.out.println(floder.getFname());
      }
        return floders;
}
}
